import fp from "fastify-plugin";
import { Level } from "level";
export default fp(function appcache(app, opt, next) {
  const { CACHE_DIR } = app.getEnvs();
  const db = new Level(CACHE_DIR, { valueEncoding: "json" });
  const cache = {
    async get(key) {
      const { value, expire, date } = await db.get(key);
      if (expire !== 0) {
        const t = Math.floor((Date.now() - date) / 1000);
        if (t > expire) {
          db.del(key);
          return null;
        }
      }
      return value;
    },
    set(key, value, expire = 0) {
      db.put(key, {
        value,
        expire,
        date: Date.now(),
      });
    },
    delete(key) {
      return db.del(key);
    },
  };
  app.decorate("cache", cache);
  next();
});
